package com.jimei.voucher.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jimei.common.ServerResponse;
import com.jimei.common.modules.Const;
import com.jimei.common.modules.PageBean;
import com.jimei.common.modules.SnowflakeIdWorker;
import com.jimei.voucher.dao.ActivityMapper;
import com.jimei.voucher.exception.VoucherException;
import com.jimei.voucher.pojo.Activity;
import com.jimei.voucher.service.ActiListService;
import com.jimei.voucher.service.ActivityService;
import com.jimei.voucher.vo.ActiListVO;
import com.jimei.voucher.vo.ActivityVO;


/**
 *
 * Service实现类
 *
 * @author jimei
 * @email 10832053@qq.com
 * @date 2018-09-07 11:02:58
 */
@Service("activityService")
public class ActivityServiceImpl implements ActivityService {
    private Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class.getSimpleName());

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActiListService actiListService;

    @Override
    public ServerResponse selectByPid(String pid) {

        Activity activity = selectActivityByPid(pid);
        if(activity == null){
            return ServerResponse.createByErrorMessage("请确认查询参数是否正确");
        }

        return ServerResponse.createBySuccess(activity);
    }

    /**
     * 按照条件获取数据
     * params中需包含sort（需要排序字段），order（排序方式 desc，asc等）
     * @param params
     * @return
     */
    @Override
    public ServerResponse<PageBean<ActivityVO>> selectListByParams(Map<String,Object> params) {

        //设置分页条件
        int page = 0;
        int pageSize = Const.DEFAULT_PAGE_SIZE;
        Object pageParams = params.get("page");
        Object pageSizeParams = params.get("pageSize");

        if(pageParams != null){
            page = Integer.valueOf(pageParams.toString());
        }
        if(pageSizeParams != null){
            pageSize = Integer.valueOf(pageSizeParams.toString());
        }

        PageHelper.startPage(page, pageSize);
        List<Activity> sourceList = activityMapper.selectListByParams(params);

        //分页数据封装
        List<ActivityVO> resultList = Lists.newArrayList();
        for(Activity activity : sourceList){
            resultList.add(activity.toVO(null));
        }
        PageBean pageResult = new PageBean(sourceList);
        pageResult.setList(resultList);

        return ServerResponse.createBySuccess(pageResult);
    }


    /**
     * 新增方法
     * @return
     */
    @Override
    public ServerResponse add(ActivityVO activityVo) {

        Activity activity = new Activity();
        activity.fromVO(activityVo);
        //设置pid
        activity.setPid(SnowflakeIdWorker.getInstance(0,0).nextId() + "");

        //校验参数
        checkParams(activity);
        //设置默认值
        activity.setSort(0);
        activity.setStatus(0);
        //设置image
        setActivityImage(activity);
        //名称判重
        Integer checkNameExist = activityMapper.countByName(activity.getName(),-1);
        if (checkNameExist != null && checkNameExist > 0) {
            return ServerResponse.createByErrorMessage("活动名称重复");
        }
        int addRowCount = activityMapper.insertSelective(activity);

        if(addRowCount <= 0){
            throw new VoucherException("新增数据失败");
        }

        return ServerResponse.createByErrorMessage("新增数据成功");
    }


    /**
     * 修改方法
     * @return
     */
    @Override
    public ServerResponse update(ActivityVO activityVo) {

        Activity activity = new Activity();
        activity.fromVO(activityVo);

        Integer countActivityExist = activityMapper.countByPidSelective(activityVo.getPid(), -1);
        if (countActivityExist != null && countActivityExist <= 0) {
            return ServerResponse.createByErrorMessage("pid 无效");
        }
        //校验参数
        checkParams(activity);

        //名称判重
        Map<String,Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("pid", activity.getPid());
        paramsMap.put("name", activity.getName());
        paramsMap.put("status", -1);
        Integer checkNameExist = activityMapper.countByNameAndPidSelective(paramsMap);
        if (checkNameExist != null && checkNameExist > 0) {
            return ServerResponse.createByErrorMessage("活动名称和其他活动名称重复");
        }
        //设置image
        setActivityImage(activity);
        int updateRowCount = activityMapper.updateByPidSelective(activity);

        if(updateRowCount <= 0){
            throw new VoucherException("修改数据失败");
        }

        return ServerResponse.createByErrorMessage("修改数据成功");
    }

    /**
     * 置顶活动
     * @param pid
     * @return
     */
    @Override
    public ServerResponse updateActivityTop(String pid) {
        Integer activitySort = activityMapper.selectSortByPid(pid);
        if (activitySort == null) {
            return ServerResponse.createByErrorMessage("pid无效");
        }
        Activity activity = new Activity();
        //当sort 不为0 时，是取消置顶 将sort值置为 0
        if (activitySort > 0) {
            activity.setSort(0);
        } else {
            //当sort 为 0时，是置顶 将最大sort 值查出加1
            Integer maxActivitySort = activityMapper.maxActivitySort (-1);
            activity.setSort(maxActivitySort+1);
        }
        //执行修改操作
        int updateRowCount = activityMapper.updateByPidSelective(activity);

        if(updateRowCount <= 0){
            throw new VoucherException("置顶失败");
        }

        return ServerResponse.createByErrorMessage("置顶成功");
    }


    /**
     * 删除方法
     * @return
     */
    @Override
    public ServerResponse deleteByPids(List<String> pids) {

        int deleteRowCount = activityMapper.deleteByPidSelective(pids);

        if(deleteRowCount <= 0){
            throw new VoucherException("删除数据失败");
        }

        return ServerResponse.createByErrorMessage("删除数据成功");
    }


    /**
     * 校验参数
     * @param activity
     */
    private ServerResponse checkParams (Activity activity){
        if (StringUtils.isEmpty(activity.getName())) {
            return ServerResponse.createByErrorMessage("名称不能为空");
        }
        if (activity.getVoucherMode() == null) {
            return ServerResponse.createByErrorMessage("券类型不能为空");
        }
        if (activity.getAmount() == null) {
            return ServerResponse.createByErrorMessage("价格不能为空");
        }
        if (activity.getType() == null) {
            return ServerResponse.createByErrorMessage("活动类型不能为空");
        }
        if (activity.getCount() == null && activity.getCount() > 0) {
            return ServerResponse.createByErrorMessage("总套数不能为空");
        }
        if (activity.getRebuy() == null) {
            return ServerResponse.createByErrorMessage("是否可重复购买不能为空");
        }
        if (activity.getStartTime() == null) {
            return ServerResponse.createByErrorMessage("开始时间不能为空");
        }
        if (activity.getEndTime() == null) {
            return ServerResponse.createByErrorMessage("结束时间不能为空");
        }

        if (new Date().after(activity.getStartTime())) {
            return ServerResponse.createByErrorMessage("活动开始时间不得早于当前时间");
        }
        if (activity.getStartTime().after(activity.getEndTime())) {
            return ServerResponse.createByErrorMessage("活动结束时间不得早于开始时间");
        }
        return null;
    }

    /**
     * 设置image
     * @param activity
     */
    private void setActivityImage (Activity activity) {
        String banner = activity.getBanner();
        if (!StringUtils.isEmpty(banner)) {
            String[] imageUrls = banner.split(",");
            activity.setImg(imageUrls[0]);
        }
    }

    /**
     * 通过pid获取对象
     * @param pid
     * @return
     */
    private Activity selectActivityByPid(String pid) {
        Activity activity = activityMapper.selectByPid(pid);
        return activity;
    }

    @Override
    public ServerResponse<ActivityVO> selectDetail(String id) {
        if(StringUtils.isBlank(id)) {
            return ServerResponse.createByErrorMessage("参数异常");
        }
        Activity activity = selectActivityByPid(id);
        if(activity == null) {
            return ServerResponse.createByErrorMessage("活动不存在");
        }
        List<ActiListVO> actiListVOs = actiListService.selectActivityList(id);
        if(actiListVOs == null || actiListVOs.isEmpty()) {
            return ServerResponse.createByErrorMessage("活动状态异常");
        }
        ActivityVO vo = new ActivityVO();
        activity.toVO(vo);
        vo.setActiListVOs(actiListVOs);
        return ServerResponse.createBySuccess(vo);
    }
}
